package com.captcha.utils;

import java.io.*;

/**
 * @Author: 随风飘的云
 * @Description: Base64工具类，详情请参考：https://www.cnblogs.com/smile361/p/6362075.html
 * @Date: 2022/2/20 12:54
 * @Modified By:
 */
public class Base64Utils {

    // 基线长度
    private static final int BASELENGTH = 128;
    // 外观长度
    private static final int LOOKUPLENGTH = 64;
    // 24位集团
    private static final int TWENTYFOURBITGROUP = 24;
    // 8位
    private static final int EIGHTBIT = 8;
    // 6位
    private static final int SIXTEENBIT = 16;

    private static final int FOURBYTE = 4;

    private static final int SIGN =  -128;

    private static final char PAD = '=';

    // 转换表
    private static byte[] base64Alphabet = new byte[BASELENGTH];

    // 字符对照表
    private static char[] lookUpBase64Alphabet = new char[LOOKUPLENGTH];

    // 文件读取缓冲区大小
    private static final int FILE_SIZE = 1024;

    static {
        // 根据ASCII表初始化整个base64Alphabet对照表，详情请参考：
        // https://baike.baidu.com/item/base64/8545775?fr=aladdin 的转换表
        // 例如ASCII表中90对应（大写）Z，则base64Alphabet[90] = 25,对应于转换表中的（大写）Z
        for (int i = 0; i < BASELENGTH; i++) {
            base64Alphabet[i] = -1;
        }
        for (int i = 'Z'; i >= 'A'; i--) {
            base64Alphabet[i] = (byte)(i - 'A');
        }
        for (int i = 'z'; i >= 'a'; i--) {
            base64Alphabet[i] = (byte)(i - 'a' + 26);
        }
        for (int i = '9'; i >= '0'; i--) {
            base64Alphabet[i] = (byte)(i - '0' + 52);
        }
        base64Alphabet['+'] = 62;
        base64Alphabet['/'] = 63;

        // 初始化所有的base64的转换表
        for (int i = 0; i <= 25; i++) {
            lookUpBase64Alphabet[i] = (char)('A' + i);
        }
        for (int i = 26, j = 0; i <= 51 ; i++, j++) {
            lookUpBase64Alphabet[i] = (char)('a' + j);
        }
        for (int i = 52, j = 0; i <= 61; i++, j++) {
            lookUpBase64Alphabet[i] = (char)('0' + j);
        }
        lookUpBase64Alphabet[62] = '+';
        lookUpBase64Alphabet[63] = '-';
    }

    /**
     * 判断是否为空格
     * @param oct
     * @return
     */
    public static boolean isWhiteSpace(char oct){
        return oct == 0x20 || oct == 0xd || oct == 0xa || oct == 0x9;
    }

    /**
     * 判断是否为等号
     * @param oct
     * @return
     */
    public static boolean isPad(char oct) {
        return oct == PAD;
    }

    /**
     * 判断是否是输入ASCII表的字符
     * @param oct
     * @return
     */
    public static boolean isData(char oct){
        return oct < BASELENGTH && base64Alphabet[oct] != -1;
    }

    public static boolean isBase(String data){
        return isArrayBase64(data.getBytes());
    }

    public static boolean isBase(byte data){
        return data == PAD || base64Alphabet[data] != -1;
    }

    /**
     * 判断是属于base64格式类型的。
     * @param data
     * @return
     */
    public static boolean isArrayBase64(byte[] data){
        int len = data.length;
        if(len == 0){
            return true;
        }
        for (int i = 0; i < len; i++) {
            if(!isBase(data[i])){
                return false;
            }
        }
        return true;
    }

    /**
     * Encodes hex octects into Base64
     * 编码
     * @param binaryData Array containing binaryData
     * @return Encoded Base64 array
     */
    public static String encode(byte[] binaryData)
    {
        if (binaryData == null)
        {
            return null;
        }

        int lengthDataBits = binaryData.length * EIGHTBIT;
        if (lengthDataBits == 0)
        {
            return "";
        }

        int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
        int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
        int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberTriplets;
        char encodedData[] = null;

        encodedData = new char[numberQuartet * 4];

        byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;

        int encodedIndex = 0;
        int dataIndex = 0;

        for (int i = 0; i < numberTriplets; i++)
        {
            b1 = binaryData[dataIndex++];
            b2 = binaryData[dataIndex++];
            b3 = binaryData[dataIndex++];

            l = (byte) (b2 & 0x0f);
            k = (byte) (b1 & 0x03);

            byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
            byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
            byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc);

            encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
            encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
            encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3];
            encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];
        }

        // form integral number of 6-bit groups
        if (fewerThan24bits == EIGHTBIT)
        {
            b1 = binaryData[dataIndex];
            k = (byte) (b1 & 0x03);
            byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
            encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
            encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4];
            encodedData[encodedIndex++] = PAD;
            encodedData[encodedIndex++] = PAD;
        }
        else if (fewerThan24bits == SIXTEENBIT)
        {
            b1 = binaryData[dataIndex];
            b2 = binaryData[dataIndex + 1];
            l = (byte) (b2 & 0x0f);
            k = (byte) (b1 & 0x03);

            byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
            byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);

            encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
            encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
            encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2];
            encodedData[encodedIndex++] = PAD;
        }
        return new String(encodedData);
    }

    /**
     * 解码成功
     * @param str 传入需要解码的str，
     * @param charset 解码后返回的格式
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String decode(String str, String charset) throws UnsupportedEncodingException {
        String result = null;
        if(!str.isEmpty()){
            byte[] bytes = decode(str);
            if(bytes != null && bytes.length > 0){
                result = new String(bytes, charset);
            }
        }
        return result;
    }

    /**
     * Decodes Base64 data into octects
     * 解码
     * @param encoded string containing Base64 data
     * @return Array containind decoded data.
     */
    public static byte[] decode(String encoded)
    {
        if (encoded == null)
        {
            return null;
        }

        char[] base64Data = encoded.toCharArray();
        // remove white spaces
        int len = removeWhiteSpace(base64Data);

        if (len % FOURBYTE != 0)
        {
            return null;// should be divisible by four
        }

        int numberQuadruple = (len / FOURBYTE);

        if (numberQuadruple == 0)
        {
            return new byte[0];
        }

        byte decodedData[] = null;
        byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;
        char d1 = 0, d2 = 0, d3 = 0, d4 = 0;

        int i = 0;
        int encodedIndex = 0;
        int dataIndex = 0;
        decodedData = new byte[(numberQuadruple) * 3];

        for (; i < numberQuadruple - 1; i++)
        {

            if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))
                    || !isData((d3 = base64Data[dataIndex++])) || !isData((d4 = base64Data[dataIndex++])))
            {
                return null;
            } // if found "no data" just return null

            b1 = base64Alphabet[d1];
            b2 = base64Alphabet[d2];
            b3 = base64Alphabet[d3];
            b4 = base64Alphabet[d4];

            decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
            decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
            decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
        }

        if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++])))
        {
            return null;// if found "no data" just return null
        }

        b1 = base64Alphabet[d1];
        b2 = base64Alphabet[d2];

        d3 = base64Data[dataIndex++];
        d4 = base64Data[dataIndex++];
        if (!isData((d3)) || !isData((d4)))
        {// 检测是否为等号
            if (isPad(d3) && isPad(d4))
            {
                if ((b2 & 0xf) != 0)// last 4 bits should be zero
                {
                    return null;
                }
                byte[] tmp = new byte[i * 3 + 1];
                System.arraycopy(decodedData, 0, tmp, 0, i * 3);
                tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
                return tmp;
            }
            else if (!isPad(d3) && isPad(d4))
            {
                b3 = base64Alphabet[d3];
                if ((b3 & 0x3) != 0)// last 2 bits should be zero
                {
                    return null;
                }
                byte[] tmp = new byte[i * 3 + 2];
                System.arraycopy(decodedData, 0, tmp, 0, i * 3);
                tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
                tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
                return tmp;
            }
            else
            {
                return null;
            }
        }
        else
        { // No PAD e.g 3cQl
            b3 = base64Alphabet[d3];
            b4 = base64Alphabet[d4];
            decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
            decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
            decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);

        }
        return decodedData;
    }

    private static int removeWhiteSpace(char[] data) {
        if (data == null)
        {
            return 0;
        }

        // count characters that's not whitespace
        int newSize = 0;
        int len = data.length;
        for (int i = 0; i < len; i++)
        {
            if (!isWhiteSpace(data[i]))
            {
                data[newSize++] = data[i];
            }
        }
        return newSize;
    }

    /**
     * 文件转换为二进制数组
     * @param path
     * @return
     * @throws FileNotFoundException
     */
    public static byte[] fileToByte(String path) throws IOException {
        byte[] data = new byte[0];
        File file = new File(path);
        if(file.exists()){
            FileInputStream inputStream = new FileInputStream(file);
            // 输入缓冲区
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream(2048);
            // 缓冲数组大小
            byte[] cache = new byte[FILE_SIZE];
            int read = 0;
            while ((read = inputStream.read(cache)) != -1){
                // 写入缓冲数组
                outputStream.write(cache, 0, read);
                // 重新刷新缓冲区
                outputStream.flush();
            }
            inputStream.close();
            outputStream.close();
            data = outputStream.toByteArray();
        }
        return data;
    }

    /**
     * 二进制数组转文件
     * @param bytes
     * @param path
     * @throws IOException
     */
    public static void ByteToFile(byte[] bytes, String path) throws IOException {
        // 文件输入缓冲区
        InputStream inputStream = new ByteArrayInputStream(bytes);
        File file = new File(path);
        // 判断父目录是否存在，不存在则创建文件目录
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        // 创建文件
        file.createNewFile();
        // 输出缓冲区
        OutputStream outputStream = new FileOutputStream(file);
        byte[] cache = new byte[FILE_SIZE];
        int read = 0;
        while ((read = inputStream.read(cache)) != -1){
            outputStream.write(cache, 0, read);
            outputStream.flush();
        }
        inputStream.close();
        outputStream.close();
    }

    /**
     * 文件转String类型的base64数据
     * @param path
     * @return
     * @throws IOException
     */
    public static String encodeFile(String path) throws IOException {
        byte[] data = fileToByte(path);
        return encode(data);
    }

    /**
     * 二进制数据转文件
     * @param path
     * @param base
     * @throws IOException
     */
    public static void decodeFile(String path, String base) throws IOException {
        byte[] base64 = decode(base);
        ByteToFile(base64, path);
    }
}
